const request = require('request')
var crypto = require('crypto')
const config = {
  clientId: '',
  appSecret: '',
  apiHostname: 'https://gw-api.pinduoduo.com/api/router'
}

class PddClient {
  constructor (props) {
    this.config = Object.assign(config, props)
  }

  execute (type = '', params = {}) {
    return new Promise((resolve, reject) => {
      const data = {
        type: type,
        timestamp: (Date.now() / 1000).toFixed(0),
        data_type: 'JSON',
        client_id: this.config.clientId

      }

      Object.assign(data, params)
      const sortedData = {}
      let urlParams = ''
      Object.keys(data).sort().forEach(v => {
        sortedData[v] = data[v]
        urlParams += '&' + v + '=' + encodeURIComponent(data[v])
      })
      sortedData.sign = this.sign(sortedData)
      request.post(this.config.apiHostname + `?sign=${sortedData.sign}` + urlParams, { 'Content-type': 'application/json' }, (err, res, body) => {
        if (body && body.error_response) {
          console.warn('拼多多接口请求错误: ', body.error_response)
          reject(body)
        } else if (body && !body.error_response) {
          resolve(body)
        }
      })
    })
  }

  sign (params) {
    let str = ''
    Object.keys(params).forEach((v) => {
      str += v + params[v]
    })

    return crypto.createHash('md5')
      .update(this.config.appSecret + str + this.config.appSecret)
      .digest('hex')
      .toUpperCase()
  }
}

module.exports = PddClient
